import { _decorator, Component, Node, Sprite, Label, Vec3, v3, Color, SpriteFrame, UITransform } from 'cc';
const { ccclass, property } = _decorator;

import { GameData } from "../Data/GameData";
import { BlockType, PosType } from "../Data/GameEnum";
import Grid from "./Grid";
import { MaterialData } from "../Config/MaterialData";
import { Consts } from "../Data/Consts";
import { bdlMgr } from "../Manager/SS_BundleManager";

@ccclass('Block')
export default class Block extends Component {
    @property(Node)
    normal: Node | null = null;
    @property(Sprite)
    icon: Sprite | null = null;
    @property(Label)
    Label_point: Label | null = null;

    blockType: BlockType = BlockType.NORMAL;
    x: number = 0;
    y: number = 0;
    length: number = 1;
    id: number = 0;
    color: number = 0;
    point: number;
    is装填 = false;
    is装填完成 = false;
    isDead: boolean = false;
    startPos;
    grid: Grid = null;
    canMove: boolean = true;
    newPosition: Vec3;
    initPosition: Vec3;
    create_x;

    init(_blockType: BlockType, _posType: PosType, _x: number, _y: number, _point: number, _id: number) {
        this.blockType = _blockType;
        this.x = _x;
        this.create_x = this.x;
        this.y = _y;
        this.point = _point;
        this.id = _id;

        this.node.active = true;

        this.node.position = v3(0, 0, 0);

        this.startPos = this.node.position;

        this.RefreshSprite();
    }

    async RefreshSprite() {
        const item_data = MaterialData.find(e => e.id === this.id);

        bdlMgr.getRes<SpriteFrame>(Consts.BundleName.SPRITE, `main/material/icon/${item_data.icon}/spriteFrame`, SpriteFrame).then(res => { this.icon.spriteFrame = res });

        this.icon.sizeMode = Sprite.SizeMode.TRIMMED;

        this.icon.node.getComponent(Sprite).color = new Color().fromHEX(`#484848`);
    }

    GetXByX(x_pos: number) {
        let x = (x_pos - (-GameData.W / 2 + this.node.getComponent(UITransform).width / 2)) / GameData.cell_width + 0.5;
        let x_int = Math.floor(x);
        return x_int;
    }

    GetXByY(y_pos: number) {
        let y = (y_pos - (-GameData.H / 2 + this.node.getComponent(UITransform).height / 2)) / GameData.cell_height + 0.5;
        let x_int = Math.floor(y);
        return x_int;
    }
    
    Destroy() {
        this.node.destroy();
    }
}